package org.jflame.commons.file;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.spi.FileTypeDetector;

import net.sf.jmimemagic.Magic;
import net.sf.jmimemagic.MagicException;
import net.sf.jmimemagic.MagicMatch;
import net.sf.jmimemagic.MagicMatchNotFoundException;
import net.sf.jmimemagic.MagicParseException;

/**
 * 基于Jmimemagic包实现FileTypeDetector接口,如果无法判断或过程出现异常采用文件扩展名检测
 * 
 * @author charles.zhang
 * @see java.nio.file.spi.FileTypeDetector
 * @see Files.probeContentType(Path)
 */
public class JmimemagicFileTypeDetector extends FileTypeDetector {

    @Override
    public String probeContentType(Path path) throws IOException {
        File tmpFile = path.toFile();
        try {
            MagicMatch match = Magic.getMagicMatch(tmpFile, false);
            return match.getMimeType();
        } catch (MagicParseException e) {
            e.printStackTrace();
        } catch (MagicMatchNotFoundException e) {
            e.printStackTrace();
        } catch (MagicException e) {
            e.printStackTrace();
        }
        return MimeTypes.getInstance()
                .getMimetype(tmpFile.getName());
    }

}
